package asorm.db.event
{
	import flash.events.Event;
	import asorm.db.LocalDatabase;
	import flash.data.SQLStatement;
	import mx.collections.ArrayCollection;
	import flash.data.SQLResult;
	import asorm.util.string.StringUtil;

	public class LocalDatabaseEvent extends Event
	{
		public static const DATABASE_OPENED:String = "databaseOpened";
		public static const DATABASE_SQL_EXECUTED:String = "databaseSQLExecuted";
        public static const DATABASE_SQL_FAILED:String = "databaseSQLFailed";
        
        public static const QUERYTYPE_NULL:int = -1;
        public static const QUERYTYPE_SELECT:int = 0;
        public static const QUERYTYPE_INSERT:int = 1;
        public static const QUERYTYPE_UPDATE:int = 2;
        public static const QUERYTYPE_DELETE:int = 3;
        public static const QUERYTYPE_DROP:int = 4;
        public static const QUERYTYPE_CREATE_TABLE:int = 5;

		/** The database involved in this event */
        public var localDatabase:LocalDatabase;
                
        /** The query type */
        public var queryType:int;

		/** the result */
        public var result:SQLResult;

		/**
		 * Constructs a new DatabaseEvent instance
		 * @param type - the event type
		 * @param ldb - the LocalDatabase instance involved in the event
		 */
		public function LocalDatabaseEvent(type:String, ldb:LocalDatabase=null)
		{
			super(type);
			localDatabase = ldb;
			_sqlStatement = null;
			result = null;
			queryType = QUERYTYPE_NULL;
		}

        override public function clone():Event {
            var event:LocalDatabaseEvent = new LocalDatabaseEvent(type, localDatabase);
            event.sqlStatement = _sqlStatement;
            return event;
        }
		
		public function get sqlStatement(): SQLStatement {
			return _sqlStatement;
		}
		
		public function set sqlStatement(stmt:SQLStatement): void {
			this._sqlStatement = stmt;
			if (StringUtil.startsWith(stmt.text, "SELECT")) {
				this.queryType = QUERYTYPE_SELECT;
			}
			else if (StringUtil.startsWith(stmt.text, "INSERT")) {
				this.queryType = QUERYTYPE_INSERT;
			}
			else if (StringUtil.startsWith(stmt.text, "UPDATE")) {
				this.queryType = QUERYTYPE_UPDATE;
			}
			else if (StringUtil.startsWith(stmt.text, "DELETE")) {
				this.queryType = QUERYTYPE_DELETE;
			}
			else if (StringUtil.startsWith(stmt.text, "DROP")) {
				this.queryType = QUERYTYPE_DROP;
			}
			else if (StringUtil.startsWith(stmt.text, "CREATE TABLE")) {
				this.queryType = QUERYTYPE_CREATE_TABLE;
			}
		}
		
        /** The SQLStatement instance involved in this event */
        private var _sqlStatement:SQLStatement;
		
	}
}
